package com.phonegap.plugin;

import java.io.File;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.util.Log;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import com.phonegap.api.PluginResult.Status;

public class PhoneGapPlugin extends Plugin {

	public static final String LIST_ACTION = "list";
	public static final String START_ACTIVITY_ACTION = "startactivity";

	@Override
	public PluginResult execute(String action, JSONArray data, String callbackId) {
		
		Log.d("PhoneGapPlugin", "Plugin Called");

		PluginResult result = null;

		if (LIST_ACTION.equals(action)) {
			try {
				Log.d("PhoneGapPlugin", "action called:  " + LIST_ACTION);
				String fileName = data.getString(0);
				JSONObject fileInfo = getDirectoryListing(fileName, new File(fileName));

				Log.d("PhoneGapPlugin", "Returning " + fileInfo.toString());

				result = new PluginResult(Status.OK, fileInfo);

			} catch (JSONException jsonEx) {

				Log.d("PhoneGapPlugin", "Got JSON Exception " + jsonEx.getMessage());

				result = new PluginResult(Status.JSON_EXCEPTION);
			}
		}else if (START_ACTIVITY_ACTION.equals(action)){
			try {
				Log.d("PhoneGapPlugin", "action called:  " + START_ACTIVITY_ACTION);
				String fileName = data.getString(0);
				Intent i = new Intent(this.ctx, VideoViewDemo.class);
				i.putExtra("name", fileName);				
				this.ctx.startActivity(i);
				
			} catch (JSONException e) {
				Log.d("Action: " + START_ACTIVITY_ACTION, " is exception ");				
			}				
			result = new PluginResult(Status.OK);			
			
		}else {
			
			result = new PluginResult(Status.INVALID_ACTION);
			Log.d("PhoneGapPlugin", "Invalid action : " + action + " passed");
		}	
		
		return result;		 		
				
	}

	private JSONObject getDirectoryListing(String fileName, File file) throws JSONException {

		JSONObject fileInfo = new JSONObject();
		fileInfo.put("filename", fileName);
		fileInfo.put("isdir", file.isDirectory());
		if (file.isDirectory()) {
			JSONArray children = new JSONArray();
			fileInfo.put("children", children);			
			if (null != file.listFiles()) {
				for (File child : file.listFiles()) {
					JSONObject childInfo = new JSONObject();
					childInfo.put("filename",child.getName());
					childInfo.put("isdir",child.isDirectory());
					children.put(childInfo);
				}
			}
		}
		return fileInfo;
	}
}
